Bean 설정과 Scope

✒️ 2025-06-27 00:39 내용 수정


참고 자료 : Spring Bean Overview, Spring Container Overview
Spring Framework 문서도 참고.

Bean

Spring Container에서 관리하는 애플리케이션의 객체


Bean 생성

@Configuration + @Bean

@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }

	// 의존성 추가한 Bean
	@Bean
	public TestService testService(TestRepository testRepository) {
		return new TestService(testRepository);
	}

	@Bean("myBean")
	public TestBean testBean() {
		return new TestBean();
	}
}

XML 파일 설정

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> 
	<bean id="빈이름" class="클래스전체경로"> 
		<!-- bean 설정 -->
	</bean> 

	<bean id="myService" class="com.example.MyService"> 
		<!-- bean 설정 -->
	</bean> 
</beans>

Bean Scope

Scope 이름 설명 사용 시점/라이프사이클
singleton 기본값. (Singleton 디자인 패턴과 비슷)
IoC 컨테이너당 단일 객체 인스턴스를 1회 생성.
모든 요청에서 동일한 인스턴스 제공
애플리케이션 전역, stateless 서비스
prototype 요청할 때마다 새 인스턴스 생성.
Spring이 파괴는 관리하지 않음
상태 저장 객체 등
request HTTP 요청이 시작될 때 새 인스턴스 생성.
요청 종료 시 폐기
웹 요청 당 상태 관리
session HTTP 세션당 하나의 인스턴스.
세션 종료 시 폐기
사용자별 세션 상태 저장
application ServletContext 당 하나 생성.
웹 애플리케이션 전체에서 공유
앱 전역 설정/상태
websocket WebSocket session 생명 주기와 연관됨 Portlet 환경에서 사용
@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }

	@Bean
	@Scope("prototype")
	public TestService testService() {
		return new TestService();
	}

	@Bean
	@SessionScope
	public TestBean testBean() {
		return new TestBean();
	}
}
<bean id="myService" class="com.example.MyService" scope="singleton"/>
<bean id="testBean" class="com.example.TestBean" scope="session"/>